<template>
    <el-upload class="avatar-uploader" action="" :http-request="reqimg" :show-file-list="false"
        :before-upload="beforeAvatarUpload">
        <img v-if="value" :src="value" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</template>


<script>
import COS from 'cos-js-sdk-v5';
export default {
    props: {
        value: {
            tpye: String,
            default: ''
        }
    },
    methods: {
        //头像上传之前
        beforeAvatarUpload(file) {
            //jpgt png gif bmp
            const filetpye = ['image/jpeg', 'image/bmp', 'image/gif', 'image/png']
            //文件的类型
            const isJPG = filetpye.includes(file.type)
            //文件的大小
            const isLt2M = file.size / 1024 / 1024 < 5;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 jpgt png gif bmp 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        //上传文件
        reqimg(params) {
            const file = params.file
            //完成COS初始化
            const cos = new COS({
                SecretId: 'AKID53pQuJYaTJzTjmz5yiOvFMI1Zv66sQ1g',
                SecretKey: 'mPsDOOFF7mDTXQRUTIzWu9EANfjaFixz'
            })
            cos.putObject({
                Bucket: 'wygtxy-1324562131',//存储桶的名称
                Region: 'ap-guangzhou',//地域
                Key: file.name,//文件名称
                StorageClass: 'STANDARD',//固定值
                Body: file//文件对象
            }, (err, data) => {
                //判断是否获取到了图片的地址
                if (data.statusCode === 200 && data.Location) {
                    //组件中绑定了v-model属性  会默认产生一个自定义事件为input
                    this.$emit('input', 'http://'+ data.Location)
                }
                else{
                    this.$message.error(err.message)
                }
            })
        }
    }
}
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
